﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace IEx
{
    public class Setting
    {
        public static object lockObject = new object();
        public IEnumerable<SourceItem> LoadAll()
        {
            string startUpPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            string xmlPath = Path.Combine(startUpPath, "sourceconfig.xml");
            if (File.Exists(xmlPath))
            {
                XmlReaderSettings readerSettings = new XmlReaderSettings();
                readerSettings.IgnoreComments = true;

                XmlReader reader = XmlReader.Create(xmlPath, readerSettings);

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(reader);
                XmlNodeList socials = xmlDoc.GetElementsByTagName("source");
                List<SourceItem> listSourceMaps = new List<SourceItem>();

                foreach (XmlNode company in socials)
                {
                    XmlNodeList sourceMaps = company.ChildNodes;
                    foreach (XmlNode source in sourceMaps)
                    {
                        string sourceCode = company.Attributes["code"].Value;
                        int languageId = int.Parse(source.Attributes["lang"].Value);

                        SourceItem dataFeed = new SourceItem(
                            source.Attributes["url"].Value,
                            languageId,
                            sourceCode,
                            source.Attributes["searchcode"].Value,
                            int.Parse(source.Attributes["sourceid"].Value),
                            source.Attributes["datetimeformat"].Value);

                        if (source.Attributes["dailyurl"] != null)
                            dataFeed.DailyUrl = source.Attributes["dailyurl"].Value;
                        //Read parser type and request builder type
                        if (source.Attributes["htmlParserType"] != null)
                        {
                            dataFeed.HtmlParserType = source.Attributes["htmlParserType"].Value;
                        }

                        if (source.Attributes["requestBuilderType"] != null)
                        {
                            dataFeed.RequestBuilderType = source.Attributes["requestBuilderType"].Value;
                        }

                        listSourceMaps.Add(dataFeed);
                    }
                }
                reader.Close();
                return listSourceMaps;
            }
            else
            {
                throw new Exception("sourceconfig.xml is not found");
            }
        }
    }
}
